package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.service.UserRegisterService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author LIN
 * @date 2022-03-15
 */
@RestController
@RequestMapping(value = "/user")
public class UserRegisterController {


    private static final Lock lock = new ReentrantLock(true);

    private static final Lock readLock = new ReentrantReadWriteLock().readLock();

    private static final Lock writeLock = new ReentrantReadWriteLock().writeLock();


    @Resource
    private UserRegisterService userRegisterService;

    @RequestMapping(value = "/register")
    public String register(User user){
        try{
            writeLock.lock();
            System.out.println(Thread.currentThread().getName()+"获取了写锁");
            readLock.lock();
            System.out.println(Thread.currentThread().getName()+"获取了读锁");
            userRegisterService.register(user);
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放了读锁");
            readLock.unlock();
            System.out.println(Thread.currentThread().getName()+"释放了写锁");
            writeLock.unlock();
        }

        return "[controller]注册用户成功！";
    }

    @RequestMapping(value = "txTest",method = RequestMethod.GET)
    public String txTest(){

        userRegisterService.t1();
        return "测试事务传播";
    }

    @RequestMapping(value = "/demo",method = RequestMethod.GET)
    public String qualifyTest(){
        userRegisterService.qualifyTest();
//        demo2.print();
        return "bean别名测试";
    }

}
